import { ElMessage } from "element-plus";
import { defineStore, Store } from "pinia";
import storage from "@/utils/storage";
import * as utils from "@/utils/utils";

// 合并歌曲到播放列表查重
const concatPlayList: any = (list: any, playList = []) => {
  // filter过滤无版权及vip歌曲
  return utils.concatPlayList(
    list.filter((item: any) => {
      return !item.license && !item.vip;
    }),
    playList
  );
};
// 当前歌曲在播放列表的索引
const findIndex = (list: any, playList: any) => {
  return playList.findIndex((d: any) => {
    return d.id === list.id;
  });
};

export const useHomeStore = defineStore("home", {
  state: () => ({
    isLogin: false, // 是否登录
    loginDialogVisible: false, // 登录弹窗显示与隐藏
    isPlayed: false, // 当前播放状态
    playList: storage.getItem("playList") || [], // 播放列表
    userInfo: storage.getItem("userInfo") || {}, // 登录用户信息
    playIndex: storage.getItem("playIndex") || 0, // 当前播放歌曲在播放列表的所有位置
    isShowPlayListTips: false, // 添加及播放成功后，播放列表按钮提示的文字
  }),
  getters: {},
  actions: {
    async setLoginDialog(val: any) {
      this.loginDialogVisible = val;
    },
    // 播放当前选中的歌曲
    async selectPlay(list: any) {
      const playList: any = await concatPlayList(list, this.playList);
      this.SET_PLAYLIST(playList);
      this.SET_PLAYSTATUS(true);
      this.SET_PLAYINDEX(findIndex(list[0], playList));
    },
    // 添加歌曲到当前播放列表
    addList(list: any) {
      const playList = concatPlayList(list, this.playList);
      this.SET_PLAYLIST(playList);
      this.SET_PLAYLISTTIPS(true);
      ElMessage.success("添加列表成功");
    },
    // 播放歌曲列表里全部歌曲（清空当前播放列表）
    playAll(list: []) {
      this.SET_PLAYLIST(concatPlayList(list));
      this.SET_PLAYSTATUS(true);
      this.SET_PLAYINDEX(0);
    },
    SET_PLAYSTATUS(val: boolean = false) {
      this.isPlayed = val;
    },
    SET_PLAYLIST(val: any = null) {
      this.playList = val;
      storage.setItem("playList", val);
    },
    SET_PLAYINDEX(val: number = 0) {
      this.playIndex = val;
      storage.setItem("playIndex", val);
    },
    SET_PLAYLISTTIPS(val = false) {
      this.isShowPlayListTips = val;
    },
  },
});
